package com.zxy.supplier_system.server.utils.wechat.mini

import com.zxy.supplier_system.server.utils.wechat.checkErrorCode
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter
import org.springframework.web.client.RestTemplate

// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
// 在小程序中使用wx login接口返回的code换取session相关数据
private val restTemplate: RestTemplate by lazy {
    RestTemplate().apply {
        this.messageConverters.add(0, object :
                AbstractJackson2HttpMessageConverter(
                        org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json().build(),
                        org.springframework.http.MediaType.TEXT_PLAIN) {
        })
    }
}

/**
 * @param code js 中wx.login获取的code
 */
fun WechatMiniProgramHelper.code2Session(code: String): Code2SessionResponse {
    val code2SessionResponse = restTemplate.getForObject(
            "https://api.weixin.qq.com/sns/jscode2session?appid=${this.appId}&secret=${this.appSecret}&js_code=$code&grant_type=authorization_code",
            Code2SessionResponse::class.java
    )!!
    checkErrorCode(code2SessionResponse.errcode, code2SessionResponse.errmsg)
    return code2SessionResponse
}


data class Code2SessionResponse(
        val openid: String?,
        val session_key: String?,
        val unionid: String?,
        val errcode: Int,
        val errmsg: String?
)

